package com.foreveross.taskservice.infra.repository;

import java.io.Serializable;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;

import com.foreveross.taskservice.infra.ddd.domain.IBaseEntity;
/**
 * hibernateDAO基类
 * @author xiangsf wdmz433xsf@gmail.com
 * @date 2012-10-11 下午04:55:25
 * @param <T>
 * @param <PK>
 */
@Repository("entityHibernateRepository")
public class EntityHibernateRepository implements IBaseRepository {
	
	private SessionFactory sessionFactory;
	
	
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	/**
	 * log4j日志记录
	 */
	protected static Logger logger = Logger.getLogger(EntityHibernateRepository.class);
	
	protected <T extends IBaseEntity> void evictCollection(T entity){
		if(logger.isDebugEnabled()){
			logger.debug("执行BaseDao里面的evictCollection");
		}
	}
	@Override
	public <T extends IBaseEntity> T get(Class<T> clazz, Serializable id) {
		return (T) sessionFactory.getCurrentSession().get(clazz, id);
	}
	@Override
	public <T extends IBaseEntity> T find(Class<T> clazz, Serializable id) {
		return (T) sessionFactory.getCurrentSession().load(clazz, id);
	}
	@Override
	public <T extends IBaseEntity> boolean exists(Class<T> clazz, Serializable id) {
		return get(clazz, id) != null;
	}
	@Override
	public <T extends IBaseEntity> List<T> findAll(Class<T> clazz) {
		Criteria criteria=sessionFactory.getCurrentSession().createCriteria(clazz);
		return criteria.list(); //hibernate 4 我也不太懂 不知这样写对不对 
		//return this.getHibernateTemplate().loadAll(clazz);
	}

	@Override
	public <T extends IBaseEntity> void create(T o) {
		sessionFactory.getCurrentSession().save(o);
		this.evictCollection(o);
	}
	@Override
	public <T extends IBaseEntity> void update(T o) {
		sessionFactory.getCurrentSession().update(o);
		this.evictCollection(o);
	}
	@Override
	public <T extends IBaseEntity> void delete(Class<T> clazz, Serializable id) {
		this.delete(this.get(clazz, id));
	}
	@Override
	public <T extends IBaseEntity> void delete(T o) {
		sessionFactory.getCurrentSession().delete(o);
		this.evictCollection(o);
	}
	@Override
	public <T extends IBaseEntity> void save(T o) {
		sessionFactory.getCurrentSession().saveOrUpdate(o);
		this.evictCollection(o);
	}
}
